package top.ucat.x.system.service.management;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ucat.box.starter.mybatis.plus.base.service.BaseCrudServiceImpl;
import top.ucat.box.starter.oauth.common.annotation.AutoPermission;
import top.ucat.x.system.dao.api.SysUserRoleDao;
import top.ucat.x.system.entity.SysRole;
import top.ucat.x.system.entity.SysUser;
import top.ucat.x.system.entity.SysUserRole;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther: Jun
 * @Date: 2020/4/23 15:21
 * @Description:
 */
@Service
public class SysUserRoleServiceImpl extends BaseCrudServiceImpl<SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public List<SysUserRole> getUserRoles(String userId) {
        LambdaQueryWrapper<SysUserRole> wrapper = sysUserRoleDao.getWrapper().lambda().eq(SysUserRole::getUserId, userId);
        List<SysUserRole> list = sysUserRoleDao.list(wrapper);
        return list;
    }

    @Override
    public void saveUserRole(List<SysUserRole> userRoles) {
        if (userRoles != null && !userRoles.isEmpty()) {
            //删除原先这个人的所有角色
            SysUserRole sysUserRole = userRoles.get(0);
            sysUserRoleService.delUserRole(sysUserRole.getUserId());
            //保存
            userRoles.forEach(r -> {
                sysUserRoleDao.save(r);
            });
        }
    }

    @Override
    public void delUserRole(String userId) {
        LambdaQueryWrapper<SysUserRole> wrapper = sysUserRoleDao.getWrapper().lambda().eq(SysUserRole::getUserId, userId);
        sysUserRoleDao.remove(wrapper);
    }

    @Override
    public Set<String> getUserRoleSigns(String userId) {
        List<SysUserRole> userRoles = this.getUserRoles(userId);
        List<String> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> roles = sysRoleService.getRolesByIds(roleIds);
        Set<String> roleSigns = roles.stream().map(SysRole::getSign).collect(Collectors.toSet());

        SysUser sysUser = sysUserService.queryById(userId);
        if (sysUser != null && sysUser.isAdmin()) {
            roleSigns.add("admin");
        }
        return roleSigns;
    }
}
